package com.ikingtech.platform.service.push.websocket.session;

import com.ikingtech.framework.sdk.utils.Tools;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author tie yan
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WebsocketSessionManager {

    private static final Map<String, List<WebSocketSession>> CONNECTING_SESSION_POOL = new ConcurrentHashMap<>();

    public static void add(String userId, WebSocketSession session) {
        CONNECTING_SESSION_POOL.computeIfAbsent(userId, k -> new ArrayList<>()).add(session);
    }

    public static void remove(String sessionId) {
        AtomicReference<String> targetUserId = new AtomicReference<>();
        CONNECTING_SESSION_POOL.forEach((user, sessions) -> sessions.forEach(session -> {
            if (sessionId.equals(session.getId())) {
                targetUserId.set(user);
            }
        }));
        if (Tools.Str.isBlank(targetUserId.get())) {
            return;
        }
        CONNECTING_SESSION_POOL.remove(targetUserId.get());
    }

    public static List<WebSocketSession> get(String userId) {
        return CONNECTING_SESSION_POOL.get(userId);
    }
}
